/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * principal.java
 *
 * Created on 04-jul-2011, 1:10:09
 */
package clases;

import newpackage.MyempleadosExt;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Locale;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import newpackage.Mycontratos;
import newpackage.Myempleados;
import newpackage.NewHibernateUtil;


//import sakila.entity.ActorExt;
//import sakila.entity.Actor;
//import sakila.util.HibernateUtil;

/**
 *
 * @author macbookpro
 */
public class principal extends javax.swing.JFrame {

    /** Creates new form principal */
    public principal() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private static String buscarempleado="from Myempleados a where a.nombres like ";
    private static String buscarempleadoid="from Myempleados  a where a.idEmpleado="; 
  public static int condicion=0;

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jButton5 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jButton7 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(900, 450));
        setSize(new java.awt.Dimension(100, 400));
        getContentPane().setLayout(null);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(300, 20, 530, 343);

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });
        getContentPane().add(jTextField1);
        jTextField1.setBounds(10, 70, 120, 28);

        jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        jLabel1.setText("Update");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(110, 10, 80, 22);

        jLabel2.setText("Buscar Por Nombre");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(10, 40, 130, 16);

        jButton3.setText("Actualizar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3);
        jButton3.setBounds(140, 70, 107, 29);

        jLabel3.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        jLabel3.setText("Insertar");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(110, 120, 70, 22);

        jButton5.setText("Insertar");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton5);
        jButton5.setBounds(90, 160, 92, 29);

        jLabel4.setText("Inserte en la Tabla y presione en Insertar"); // NOI18N
        jLabel4.setToolTipText("Posiciones en insertar y ingrese los campos en la tabla , cuando ya haya llenado los campos, presione el boton insertar para guardar.");
        jLabel4.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jLabel4.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                jLabel4MouseMoved(evt);
            }
        });
        getContentPane().add(jLabel4);
        jLabel4.setBounds(20, 120, 270, 90);

        jLabel6.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        jLabel6.setText("Borrar");
        getContentPane().add(jLabel6);
        jLabel6.setBounds(110, 230, 60, 22);

        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });
        jTextField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField2KeyPressed(evt);
            }
        });
        getContentPane().add(jTextField2);
        jTextField2.setBounds(90, 310, 90, 28);

        jLabel5.setText("Buscar ");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(30, 300, 50, 50);

        jButton7.setText("Borrar");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton7);
        jButton7.setBounds(200, 310, 81, 29);

        jLabel7.setText("Para borrar busque el registro y presione borrar");
        jLabel7.setToolTipText("para borrar un registro seleccione en le tabla y presione borrar, sino busque por nombre y presione borrar");
        jLabel7.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jLabel7.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                jLabel7MouseMoved(evt);
            }
        });
        getContentPane().add(jLabel7);
        jLabel7.setBounds(0, 220, 300, 140);

        jLabel8.setToolTipText("presione enter dentro del campo de texto para buscar y leugo modifique en la tabla, y presione actualizar para guardar los cambios.");
        getContentPane().add(jLabel8);
        jLabel8.setBounds(10, 10, 260, 100);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    
     //  String id;
      //  id=(String)jTable1.getValueAt( jTable1.getSelectedRow(), 0);
             //executeHQLQuery(buscarempleadoid+"'"+id+"'");//busca un registro    
       
             Myempleados actualiza=new Myempleados();
             
        actualiza.setIdEmpleado(Integer.parseInt((String) jTable1.getValueAt( jTable1.getSelectedRow(), 0)));
        actualiza.setNombres(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 1)));
        actualiza.setApellidos(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 2)));
        actualiza.setEdad(Short.valueOf((String) jTable1.getValueAt( jTable1.getSelectedRow(), 3)));
        actualiza.setDireccion(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 4)));
        actualiza.setTelefonoCasa(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 5)));
         actualiza.setTelefonoCelular(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 6)));
       actualiza.setEstadoCivil(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 7)));
        actualiza.setGradoAcademico(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 8)));
    
       
        this.actualizar(actualiza);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked

        System.err.println(jTable1.getSelectedRow());
        
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed

       
        if(evt.getKeyCode()==10){
            
             executeHQLQuery(buscarempleado+"'"+jTextField1.getText()+"%"+"'");//busca un registro
        }
        
       
        
        
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1KeyPressed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:

             Myempleados actualiza=new Myempleados();
             
        actualiza.setIdEmpleado(Integer.parseInt((String) jTable1.getValueAt( jTable1.getSelectedRow(), 0)));
        actualiza.setNombres(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 1)));
        actualiza.setApellidos(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 2)));
        actualiza.setEdad(Short.valueOf((String) jTable1.getValueAt( jTable1.getSelectedRow(), 3)));
        actualiza.setDireccion(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 4)));
        actualiza.setTelefonoCasa(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 5)));
        actualiza.setTelefonoCelular(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 6)));
        actualiza.setEstadoCivil(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 7)));
        actualiza.setGradoAcademico(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 8)));
        this.insertar(actualiza);
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jLabel4MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel4MouseMoved
        // TODO add your handling code here:
//JOptionPane.showMessageDialog(null, "mierda");
   if(jTable1.isRowSelected(0)==false){
     
       
    ArrayList<String> tableHeaders = new ArrayList<String>();
    tableHeaders.add("Id_empleado"); 
    tableHeaders.add("Nombre");
    tableHeaders.add("Apellido");
    tableHeaders.add("Edad");
    tableHeaders.add("Direccion");
    tableHeaders.add("Telefonocasa");
    tableHeaders.add("Telefonocelular");
    tableHeaders.add("Estado civil");
    tableHeaders.add("Grado academico");

    DefaultTableModel model = new DefaultTableModel();
   
                    model.setColumnIdentifiers(tableHeaders.toArray());
                    model.setNumRows(1);
                    jTable1.setModel(model);

                    
                    }  
                    
   
   
   
                    
        
    }//GEN-LAST:event_jLabel4MouseMoved


    
    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField2ActionPerformed

    private void jTextField2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField2KeyPressed
   
        if (evt.getKeyCode()==10){
    
    executeHQLQuery(buscarempleado+"'"+jTextField2.getText()+"%"+"'");//busca un registro
       
         
   }
        
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField2KeyPressed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
Myempleados actualiza=new Myempleados();
             
        actualiza.setIdEmpleado(Integer.parseInt((String) jTable1.getValueAt( jTable1.getSelectedRow(), 0)));
        actualiza.setNombres(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 1)));
        actualiza.setApellidos(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 2)));
        actualiza.setEdad(Short.valueOf((String) jTable1.getValueAt( jTable1.getSelectedRow(), 3)));
        actualiza.setDireccion(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 4)));
        actualiza.setTelefonoCasa(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 5)));
        actualiza.setTelefonoCelular(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 6)));
        actualiza.setEstadoCivil(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 7)));
        actualiza.setGradoAcademico(String.valueOf(jTable1.getValueAt( jTable1.getSelectedRow(), 8)));
        this.borrar(actualiza);        // TODO add your handling code here:
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jLabel7MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel7MouseMoved


    }//GEN-LAST:event_jLabel7MouseMoved
  
    private void executeHQLQuery(String hql) {
    try {
     
        Session session = NewHibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Query q = session.createQuery(hql);
        List resultList = q.list();
        displayResult(resultList);
        session.getTransaction().commit();
    } catch (HibernateException he) {
        he.printStackTrace();
    }
} 
  
    
        // método para desplegar la información
   private void displayResult(List resultList) {
   ArrayList<String> tableHeaders = new ArrayList<String>();
   ArrayList tableData = new ArrayList();
    
    
    tableHeaders.add("Id_empleado"); 
    tableHeaders.add("Nombre");
    tableHeaders.add("Apellido");
    tableHeaders.add("Edad");
    tableHeaders.add("Direccion");
    tableHeaders.add("Telefonocasa");
    tableHeaders.add("Telefonocelular");
    tableHeaders.add("Estado civil");
    tableHeaders.add("Grado academico");

 LinkedList<Myempleados> milista = new LinkedList<Myempleados>();
    
 for(Object o : resultList) {
        // Observar la clase usada para obtener la información
        // se puede usar directamente la clase del ORM
        // o usar una extendida como debería estar en el proyecto final
     
        Myempleados employee=(Myempleados)o;
        
        milista.addFirst(employee);
       
    
                    
   
    }
 
                    DefaultTableModel model = new DefaultTableModel();
                    model.setColumnIdentifiers(tableHeaders.toArray());
                    model.setNumRows(milista.size());
                    jTable1.setModel(model);
 
 LinkedList<Myempleados> milista2 = new LinkedList<Myempleados>();
    Myempleados empleado=new Myempleados();
    int recorre=0;
         recorre= milista.toArray().length;
  
         
for (int i=0;i<recorre;i++){
    
                    jTable1.setValueAt(String.valueOf(milista.getFirst().getIdEmpleado()), i, 0);
                   
                    jTable1.setValueAt(String.valueOf(milista.getFirst().getNombres()), i, 1);
                   
                    jTable1.setValueAt(String.valueOf(milista.getFirst().getApellidos()), i, 2);
                   
                    jTable1.setValueAt(String.valueOf(milista.getFirst().getEdad()), i, 3);
                      
                   jTable1.setValueAt(String.valueOf(milista.getFirst().getDireccion()), i, 4);
                    jTable1.setValueAt(String.valueOf(milista.getFirst().getTelefonoCasa()), i, 5);
                     jTable1.setValueAt(String.valueOf(milista.getFirst().getTelefonoCelular()), i, 6);
                      jTable1.setValueAt(String.valueOf(milista.getFirst().getEstadoCivil()), i, 7);
                       jTable1.setValueAt(String.valueOf(milista.getFirst().getGradoAcademico()), i, 8);
                       
                    milista.removeFirst();
                    System.out.println("una vez");         
             
            }


    }
    
 // metodo insertar, solo se debe llamar desde alguna acción 
    // usando adecuadamente los parámetros.
    public void insertar(Myempleados parametro)
    {
        Session session = NewHibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
       
        session.save(parametro);
        tx.commit();
      
    }
    
        public void borrar(  Myempleados borrarlo)
    {
        Session session = NewHibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
      
        
        session.delete(borrarlo);
        //session.save(a);
        tx.commit();
      
    }
        
           public void actualizar(Myempleados parametro)
    {
        Session session = NewHibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        session.update(parametro);
       // session.;
        tx.commit();
      
    }

    /**
     * @param args the command line arguments
     */
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new principal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton7;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
